package cn.com.infcn.monitor.task.jvm;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.com.infcn.monitor.bean.IFCJVMGarbageCollector;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;

/**
 * Java 虚拟机中的垃圾回收器。
 * 
 * @author jjs
 *
 */
public class JVMGarbageCollectorTask implements BaseTask {

	private static final Logger LOGGER = Logger.getLogger(JVMGarbageCollectorTask.class);

	@Override
	public List<IFCJVMGarbageCollector> execute() throws Exception {
		return jvmGarbageCollector();
	}

	public List<IFCJVMGarbageCollector> jvmGarbageCollector() {
		List<IFCJVMGarbageCollector> ifcGarbageCollectors = null;
		IFCJVMGarbageCollector ifcGC = null;
		try {
			
			List<GarbageCollectorMXBean> garbageCollectorMXBeanList = ManagementFactory.getGarbageCollectorMXBeans();
			if(garbageCollectorMXBeanList != null && garbageCollectorMXBeanList.size()>0){
				ifcGarbageCollectors = new ArrayList<IFCJVMGarbageCollector>();
				for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeanList) {
					ifcGC = new IFCJVMGarbageCollector();
					IFCBeanUtils.copyProperties(garbageCollectorMXBean, GarbageCollectorMXBean.class, ifcGC);
					ifcGC.setName(garbageCollectorMXBean.getName());
					ifcGarbageCollectors.add(ifcGC);
				}
			}
			
			return ifcGarbageCollectors;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}

		return null;
	}
	
	/*private void copyProperties(GarbageCollectorMXBean garbageCollectorMXBean, IFCJVMGarbageCollector ifcGC){
		ifcGC.setCollectionCount(garbageCollectorMXBean.getCollectionCount());
		ifcGC.setCollectionTime(garbageCollectorMXBean.getCollectionTime());
		ifcGC.setName(garbageCollectorMXBean.getName());
	}*/

	public static void main(String[] args) {
		JVMGarbageCollectorTask task = new JVMGarbageCollectorTask();
		List<IFCJVMGarbageCollector> ifcGarbageCollectors = task.jvmGarbageCollector();

		for (IFCJVMGarbageCollector ifcGarbageCollector : ifcGarbageCollectors) {
			System.out.println(ifcGarbageCollector.getName());
			System.out.println(ifcGarbageCollector.getCollectionCount());
			System.out.println(ifcGarbageCollector.getCollectionTime());
		}
	}

}
